// 服务器中间件-鉴权
import { verifyToken } from "server/utils/auth";
import { User } from 'server/models/User'

export default defineEventHandler(async (event) => {
  // 跳过登录相关路径
  if (["/api/auth/login", "/admin/login"].includes(event.path)) {
    return;
  }

  const cookies = parseCookies(event);
  const token = cookies.auth_token;

  if (token) {
    const payload = verifyToken(token);
    if (payload) {
      // 验证用户是否仍然存在且状态正常
      const user = await User.getSafeUserById(payload.userId);
      if (user && user.status == "active") {
        event.context.user = user;
        return;
      }
    }
  }

  // 检查路径前缀
  if (event.path.startsWith("/api/admin/")) {
    return createError({
      statusCode: 401,
      message: "无权限访问管理API",
    });
  }

  if (event.path.startsWith("/admin/")) {
    return sendRedirect(event, "/admin/login");
  }
});
